package net.itbaiyang.pattern.component.notification;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import net.itbaiyang.pattern.config.UniPushConfig;
import net.itbaiyang.pattern.model.TokenResponse;
import net.itbaiyang.pattern.util.CommonUtil;
import net.itbaiyang.pattern.util.SignGenerator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.*;

import static org.apache.commons.codec.digest.DigestUtils.sha256;

@Component
@Slf4j
public class NotificationComponent {

    @Value("${uni.cid-path}")
    private String cidPath;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private UniPushConfig uniPushConfig;

    /**
     * 获取token
     * 这里应该引入redis进行缓存token值
     *
     * @return 是否发送成功
     */
    public String getToken() {
        String beginTime = String.valueOf(CommonUtil.getCurrentTimestamp());
        String appkey = uniPushConfig.getAppkey();
        String mataSecret = uniPushConfig.getMasterSecret();
        String sign = SignGenerator.generateSign(appkey, beginTime, mataSecret);
        String appid = uniPushConfig.getAppId();
        String url = String.format(uniPushConfig.getTokenUrl(), appid);
        HttpHeaders headers = new HttpHeaders();
        headers.set("content-type", "application/json;charset=utf-8");
        Map<String, String> bodys = new HashMap<>();
        bodys.put("sign", sign);
        bodys.put("appkey", appkey);
        bodys.put("timestamp", beginTime);
        HttpEntity<Map<String, String>> entity = new HttpEntity<>(bodys, headers);
        new TokenResponse();
        TokenResponse body;
        try {
            ResponseEntity<TokenResponse> response = restTemplate.exchange(url, HttpMethod.POST, entity, TokenResponse.class);
            body = response.getBody();
            log.info("获取个推token，url={},body={}", url, response.getBody());
        } catch (Exception e) {
            log.error("请求失败");
            throw new RuntimeException("获取token失败！");
        }
        return Optional.ofNullable(body).map(TokenResponse::getData).map(TokenResponse.Detail::getToken).orElseThrow(() -> new RuntimeException("获取token失败！"));

    }

    public Boolean pushMessage(String message, List<String> cIds) {
        String url = uniPushConfig.getTokenUrl() + cidPath;
        HttpHeaders headers = new HttpHeaders();
        headers.set("token", getToken());
        Map<String, Object> bodys = getReqMap(message,cIds);
        try {
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(bodys, headers);
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            log.info("发送个推消息，response:{}", response.getBody());
            return response.getStatusCode().is2xxSuccessful();
        } catch (Exception e) {
            log.error("推送失败:{}", e.getMessage());
            return false;
        }
    }

    public Map<String, Object> getReqMap(String message, List<String> cIds) {

        // 创建最外层的Map
        Map<String, Object> pushRequestMap = new HashMap<>();

        // 添加request_id
        pushRequestMap.put("request_id", "xxx");

        // 创建settings Map并添加到pushRequestMap
        Map<String, Object> settingsMap = new HashMap<>();
        settingsMap.put("ttl", 7200000);
        pushRequestMap.put("settings", settingsMap);

        // 创建audience Map并添加到pushRequestMap
        // 这里应该从库里取对应的id数据
        Map<String, Object> audienceMap = new HashMap<>();
        audienceMap.put("cid", cIds);
        pushRequestMap.put("audience", audienceMap);

        // 创建notification Map
        Map<String, Object> notificationMap = new HashMap<>();
        notificationMap.put("title", "请填写通知标题");
        notificationMap.put("body", message);
        notificationMap.put("click_type", "url");
        notificationMap.put("url", "https//:xxx");

        // 创建push_message Map并添加到pushRequestMap
        Map<String, Object> pushMessageMap = new HashMap<>();
        pushMessageMap.put("notification", notificationMap);
        pushRequestMap.put("push_message", pushMessageMap);

        return pushRequestMap;
    }
}
